package com.libui.messageview

import android.content.Context
import android.graphics.drawable.GradientDrawable
import android.util.TypedValue
import android.view.Gravity
import android.view.View.OnClickListener
import android.view.animation.Animation
import com.libbase.utils.ThreadUtils
import com.libui.ButtonEx
import com.libui.IconFonts
import com.libui.R
import com.libui.TextViewEx
import razerdp.basepopup.BasePopupWindow
import razerdp.util.animation.AlphaConfig
import razerdp.util.animation.AnimationHelper
import java.util.Timer
import java.util.TimerTask

class MessageView(context: Context) :
    BasePopupWindow(context) {

    private val contentTextView: TextViewEx

    private val button: ButtonEx

    var contextText: CharSequence?
        get() {
            return contentTextView.text
        }
        set(value) {
            contentTextView.text = value
        }

    var onClickListener: OnClickListener? = null

    init {
        setContentView(R.layout.message_view)

        contentTextView = findViewById(R.id.content_text_view)
        contentTextView.text = "test"
        contentTextView.setOnClickListener {
            dismiss(true)

            onClickListener?.let { it.onClick(contentTextView) }
        }

        button = findViewById(R.id.close_button)
        IconFonts.instance.dataSource?.let {
            button.text = it.iconFonts["close"]
        }
        button.setOnClickListener {
            dismiss(true)
        }

        val shapeDrawable = contentView.background as GradientDrawable
        val typedValue = TypedValue()
        context.theme.resolveAttribute(androidx.appcompat.R.attr.colorPrimary, typedValue, true)
        shapeDrawable.setColor(typedValue.data)
        contentView.clipToOutline = true
    }

    override fun showPopupWindow() {
        setPopupGravityMode(
            BasePopupWindow.GravityMode.ALIGN_TO_ANCHOR_SIDE,
            BasePopupWindow.GravityMode.RELATIVE_TO_ANCHOR
        )
        popupGravity = Gravity.END or Gravity.BOTTOM
        setOutSideDismiss(false)
        isOutSideTouchable = true
        setBackgroundColor(android.R.color.transparent)

        super.showPopupWindow()
    }

    override fun onCreateDismissAnimation(): Animation {
        return AnimationHelper.asAnimation()
            .withAlpha(AlphaConfig.OUT)
            .toShow();
    }

    override fun onShowing() {
        super.onShowing()

        Timer().schedule(object : TimerTask() {
            override fun run() {
                ThreadUtils.instance.executeInMainThread {
                    dismiss(true)
                }
            }
        }, 2000)
    }
}